<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/8
 * Time: 14:56
 * used to test transaction and phpunit
 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Common as helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Lumen\Routing\Controller as BaseController;

class BiaoController extends BaseController{
    function __construct()
    {
        DB::connection()->enableQueryLog(); // 开启查询日志
    }
    /**
     * add a product post method
     * @param Request $request
     * remark: must param: name(length 16),account(money:0.000000000),period(int num),time_start(unixtime,not default now),time_end(unixtime,not default now),lowest_account(money),most_account(money)
     * remark: default param: status(default 1)
     */
    public function add(Request $request){
        // 不需要验证提交方式，因为路由前面已经限定了post了，也不需要一个一个判断是否存在对应值，只需要把值获取了以后，直接用validate去判断即可
        //$bad_words = "共产党,毛泽东,鸦片,白粉,AK47,枪";
        $this->validate($request,[
            'is_new_hand' => 'required|in:1,2',
            'type' => 'required|in:1,2',
            'contract_no' => 'required|exists:contract,contract_no|unique:borrow,contract_no', // 验证合同号在合同表中存在，并且在borrow表中未被使用
            'period' => 'required|digits:14|unique:borrow', // 竟然没有验证刚好14位的。。。regex:/\d{14}/
            'name' => 'required|max:8',
            'borrower_id' => 'required|numeric|exists:user,id',
            'account' => 'required|numeric',
            'style' => 'in:0',
            'apr' => 'required|numeric',
            'add_apr' => 'numeric',
            'add_apr_show' => 'required_with:add_apr',
            'lowest_account' => 'required|numeric',
            'most_account' => 'required|numeric|Bigger:lowest_account', // 自定义一个Bigger ^_^
            'time_start' => 'required|date-format:Y-m-d',
            'time_end' => 'required|date-format:Y-m-d|after_or_equal:time_start',
            'order_commend' => 'integer',
            'time_limit' => 'required|integer',
            'cycle_unit' => 'required|in:1,3'
        ]);
        $post = $request->all();
        helper::dump($post);
        $res = DB::table('borrow')->insert($post);
        $result = array('code'=>'100','msg'=>'success');
        if(!$res){
            $result = array('code'=>'-100','msg'=>'error');
        }
        echo json_encode($result);
    }

    // 不能直接这样写sql语句，会被注入。
    public function safe(Request $request){
        $post = $request->all();
//        helper::dump($post);
        $sql = sprintf(
            'UPDATE hj_user SET password = %s WHERE id = %s',
            $post['password'],
            $post['id']
        );
        echo $sql;
//        DB::table('user')->where('id',$post['id'])->update(['password'=>$post['password']]);
//        echo helper::last_query();
    }

    // lumen 事务
    public function active(Request $request){
        $res = array('code'=>'100','msg'=>'success');
        // 验证参数，标的id是否存在，标的状态是否正确
        $this->validate($request,[
            'borrow_id' => 'required|integer|exists:borrow,id',
            'status' => 'required|in:2|',
        ]);
        $borrow_id = $request->get('borrow_id');
        $status = $request->get('status');
        // 事务开始
        DB::beginTransaction();
        try{
        // 修改标的状态
        $borrow['status'] = $status;
        $bres = DB::table('borrow')->where('id',$borrow_id)->update($borrow);
        if(!$bres){
            throw new \Exception('update borrow failed');
        }
        // 修改everyday
        $eid = '1509984000';
        $every_day['total_borrow'] = 1000;
        $eres = DB::table('every_day')->where('date_time',$eid)->increment('total_borrow',$every_day['total_borrow']);//让字段自增给定值。
        if(!$eres){
            throw new \Exception('update every_day failed');
        }
        DB::commit();
        // 事务结束
        }catch (\Exception $e){
            DB::rollBack();
            $res = array('code'=>'-100','msg'=>$e->getMessage());
        }
        // 返回结果

        echo json_encode($res);

    }

    // 测试string
    public function string(Request $request){
        $str = $request->get('str');
        echo Str::ascii($str)."\n";
        echo Str::camel($str)."\n";
        var_dump(Str::contains($str,'33'))."\n";
        var_dump(Str::endsWith($str,'33'))."\n";
        var_dump(Str::finish($str,'33'))."\n";
        var_dump(Str::is($str,'33'))."\n";
        var_dump(Str::length($str))."\n";
        var_dump(Str::limit($str,6,'...'))."\n";
        var_dump(Str::words($str,2,'...'))."\n";
        var_dump(Str::lower($str))."\n";
        var_dump(Str::plural($str,2))."\n";
        var_dump(Str::random(32))."\n";
        var_dump(Str::quickRandom(32))."\n";
        var_dump(Str::upper($str))."\n";
        var_dump(Str::title($str))."\n";
        var_dump(Str::singular($str))."\n";
        echo Str::slug($str)."\n";
        echo Str::snake($str," ","_")."\n";
        echo Str::startsWith($str,"33")."\n";
        var_dump(Str::studly($str))."\n";
        var_dump(Str::macro($str,"33"))."\n";
    }

    // jsonp,查询出来所有>10000的标的
    public function json_p(Request $request){
        $result = array('code'=>'100','info'=>'success');
        $account = $request->get('account');
        $callback= $request->get('callback',true);
        $res = DB::table("borrow")->where('account','>=',$account)->join('user','user.id',"=",'borrow.borrower_id')->select('borrow.name','borrow.account','user.realname','borrow.create_time')->orderBy('borrow.account','desc')->get();
        if(!empty($res)){
            $result['info'] = $res;
        }else{
            $result = array('code'=>'-100','info'=>'no data');
        }
        $result = json_encode($result);
        echo $callback."($result)";
    }

    // 自定义的response方式
    public function json_p_response(Request $request){
        $result = array('code'=>'100','info'=>'success');
        $account = $request->get('account');
        $res = DB::table("borrow")->where('account','>=',$account)->join('user','user.id',"=",'borrow.borrower_id')->select('borrow.name','borrow.account','user.realname','borrow.create_time')->orderBy('borrow.account','desc')->get();
        if(!empty($res)){
            $result['info'] = $res;
        }else{
            $result = array('code'=>'-100','info'=>'no data');
        }
        return response()->json($result)->setCallback($request->get('callback'));
    }
}